package com.ywwxhz.lib;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.ywwxhz.model.AppInfo;
import com.ywwxhz.util.FileUtil;

import java.io.File;
import java.util.List;

public class BackupAsyncTask extends AsyncTask<List<AppInfo>, String, String> {

    private ProgressDialog dialog;
    private File file;
    private Context context;
    private int progress;

    public BackupAsyncTask(Context context, ProgressDialog dialog)
            throws Exception {
        this.context = context;
        this.dialog = dialog;
        file = FileUtil.getBackUpDir(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setProgress(0);
        progress = 0;
        dialog.show();
    }

    @Override
    protected String doInBackground(List<AppInfo>... params) {
        if (file != null && params[0].size() > 0) {
            for (AppInfo app : params[0]) {
                publishProgress(app.getLabel());
                if (FileUtil.copyFile(app.getSourceDir(), file,
                        app.getPkgName() + "_" + app.getVersionCode() + ".apk") != -1) {
                    app.setBackup(true);
                } else {
                    return app.getLabel() + "备份失败了";
                }
                app.setBackup(true);
            }
            return "选定文件备份成功";
        }
        return "没有选择备份文件";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        dialog.setProgress(++progress);
        dialog.setMessage("正在备份 " + values[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        dialog.dismiss();
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }

}
